/**
 * Created by wang.cheng on 2016/1/5.
 */
var async = require('async');
var system_splashScreenModel = mongoose.model('system_splashScreen');

var toolUtil = require('../../../common/utils/toolUtil');
module.exports.addSplashScreen = function (req, callback) {
    var input = req.body;

    async.waterfall([
        function(callbackInner){
            exports.splashScreenValuateDate(input.startDate, input.endDate,callbackInner);
            //callback(null, 'one', 'two');
            //console.log('1');
        },
        function(result, callbackInner){
            //callback(null, 'three');
            //console.log(arg1);
            //console.log(arg2);
            toolUtil.uploadImageService(null, null, req, function (err, images) {
                if (err) {
                    callback(err.message, null);
                } else {
                    var data = new Array();

                    images.forEach(function (image) {
                        if (image != null) {
                            data.push(image);
                        }
                    });

                    input.duration = Number(input.duration);
                    input.image = data[0];
                    //logger.info(input);
                    callbackInner(null,input);
                }
            })
        },
        function(input, callbackInner){
            // arg1 now equals 'three'
            //callback(null, 'done');
            //console.log(arg1);
            var systemSplashScreen = new system_splashScreenModel(input);
            systemSplashScreen.save(callbackInner);
        }
    ], function (err, result) {
        callback(err,result)
        //console.log(err,result);
        // result now equals 'done'
        //  console.log('4');
    });

    //this.splashScreenValuateDate(input.startDate, input.endDate, function (err, result) {
    //    if (err) {
    //        callback(err.message, null);
    //    } else {
    //        toolUtil.uploadImageService(null, null, req, function (err, images) {
    //            if (err) {
    //                callback(err.message, null);
    //            } else {
    //                var data = new Array();
    //
    //                images.forEach(function (image) {
    //                    if (image != null) {
    //                        data.push(image);
    //                    }
    //                });
    //
    //                input.duration = Number(input.duration);
    //                input.image = data[0];
    //
    //                logger.info(input);
    //
    //                var systemSplashScreen = new system_splashScreenModel(input);
    //                systemSplashScreen.save(callback);
    //
    //            }
    //        })
    //    }
    //});
};


module.exports.splashScreenList = function (req, callback) {
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var opt = {};
    if(req.body)
    {
        opt = req.body;
        if(!opt.duration)
        {
            delete opt.duration;
        }
        if(!opt.desc)
        {
            //{"desc" :{$regex:"xiaoqu"}}
            delete opt.desc;
        }else
        {
            opt.desc = {$regex:req.body.desc};
        }
        if(opt.startDate)
            opt.startDate = {'$gte':req.body.startDate};
        if(opt.endDate)
            opt.endDate = {'$lte':req.body.endDate};
        console.log(opt);
    }

    async.series([
        function (callbackInner) {
            system_splashScreenModel.count(opt, function (err, count) {
                if (err) {
                    return callbackInner(err, null);
                } else {
                    var temp = {count: count, totalPage: Math.ceil(count / size)};
                    callbackInner(null, temp);
                }
            });
        },
        function (callbackInner) {
            system_splashScreenModel.find(opt).limit(size).skip(index).exec(callbackInner);
        }
    ], callback);

};

exports.delSplashScreen = function (req, callback) {
    var splashScreen_id = req.params.id;
    logger.debug("splashScreen_id " + splashScreen_id);
    system_splashScreenModel.remove({_id: splashScreen_id}, callback);
}


exports.updateSplashScreen = function (req, callback) {
    var input = req.body;
    console.log("input",input);

    async.waterfall([
        function(callbackInner){
            //callback(null, 'one', 'two');
            //console.log('1');
            exports.splashScreenValuateDate(input.startDate, input.endDate,callbackInner,input._id);
        },
        function(arg1, callbackInner){
            //callback(null, 'three');
            //console.log(arg1);
            //console.log(arg2);
            console.log("日期验证通过了！");
            toolUtil.uploadImageService(null, null, req, function (err, images) {
                if (err) {
                    callback(err.message,null);
                } else {
                    var data = new Array();

                    images.forEach(function (image) {
                        if (image != null) {
                            data.push(image);
                        }
                    });

                    input.duration = Number(input.duration);
                    if (!data[0]) {
                        delete input.image;
                    }
                    else {
                        input.image = data[0];
                    }

                    logger.info(input);
                    callbackInner(null,input);

                }
            })
        },
        function(arg1, callbackInner){
            // arg1 now equals 'three'
            //callback(null, 'done');
            console.log(input._id);
            system_splashScreenModel.update({"_id": input._id}, input).exec(callbackInner);
        }
    ], function (err, result) {
        //console.log(result);
        // result now equals 'done'
        //  console.log('4');
        callback(err,result);
    });


    //this.splashScreenValuateDate(input.startDate, input.endDate, function (err, result) {
    //    if (err) {
    //        callback(err.message, null);
    //    } else {
    //        toolUtil.uploadImageService(null, null, req, function (err, images) {
    //            if (err) {
    //                callback(err.message, null);
    //            } else {
    //                var data = new Array();
    //
    //                images.forEach(function (image) {
    //                    if (image != null) {
    //                        data.push(image);
    //                    }
    //                });
    //
    //                input.duration = Number(input.duration);
    //                if (!data[0]) {
    //                    delete input.image;
    //                }
    //                else {
    //                    input.image = data[0];
    //                }
    //
    //                logger.info(input);
    //
    //                system_splashScreenModel.update({"_id": input._id}, input).exec(callback);
    //            }
    //        })
    //    }
    //});
};


exports.splashScreenValuateDate = function (startDate, endDate, callback,_id) {
    console.log(startDate);
    console.log(endDate);
    exports.validateDateOverlap(startDate, endDate, function (err, result) {

        if(err)
        {
            callback(err,null);
        }else {
            callback(result, null);
            logger.debug("有"+result+"处重叠");
        }


    },_id);
}

/***
 * 查询有几处重叠
 * @param startDate
 * @param endDate
 * @param callback(error,resoult)
 *    0s          0e
 *       As   Ae            //包含
 *          Bs         Be   //右重叠
 *Bs         Be             //左重叠
 *  overlapsSum:1 | 2 | 3
 */
exports.validateDateOverlap = function (startDate, endDate,callback,_id) {
    console.log(startDate);
    console.log(endDate);

    var start_Millisecond = (new Date(startDate)).getTime();
    var end_Millisecond = (new Date(endDate)).getTime();
    console.log(start_Millisecond);
    console.log(end_Millisecond);
    console.log("_id",_id);
        //opt = {'_id':{'$ne' : _id}}
    if(!_id)
        _id=null;
    var opt =
    {
        in:{
             '_id':{'$ne' : _id},
             "endDate": {'$gt': end_Millisecond},
             "startDate": {'$lt': start_Millisecond}
           }
         ,
        left:{
            '_id':{'$ne' : _id},
            "endDate": {'$gt': end_Millisecond},
            "startDate": {'$lt': end_Millisecond}
        },
        right:
        {
            '_id':{'$ne' : _id},
            "endDate": {'$gt': start_Millisecond},
            "startDate": {'$lt': start_Millisecond}
        },
        out:
        {
            '_id':{'$ne' : _id},
            "endDate": {'$lt': end_Millisecond},
            "startDate": {'$gt': start_Millisecond}
        }

    }
    if (start_Millisecond <= end_Millisecond) {

        async.series({
            "in": function (innerCallback) {

                //"endDate": {'$gte': ISODate("2016-04-23T00:00:00.000Z")},
                //"startDate": {'$lte': ISODate("2016-04-23T00:00:00.000Z")}

                //system_splashScreenModel.find({
                //    "endDate": {'$gte': end_Millisecond},
                //    "startDate": {'$lte': start_Millisecond}
                //}).count().exec(innerCallback);
                system_splashScreenModel.find(opt.in).count().exec(innerCallback);
            },
            "left": function (innerCallback) {
                system_splashScreenModel.find(opt.left).count().exec(innerCallback)
            },
            "right": function (innerCallback) {
                system_splashScreenModel.find(opt.right).count().exec(innerCallback)
            },
            "out":function(innerCallback)
            {
                system_splashScreenModel.find(opt.out).count().exec(innerCallback)
            }
        }, function (err, results) {
            if (err) callback(err, null);
            else {
                console.log(results.in + results.left + results.right+results.out);
                callback(err, results.in + results.left + results.right+results.out);
            }

        });
    }
    else {
        console.log('startDate > endDate');
        callback('startDate > endDate', null);
    }
};

exports.splashScreenLatestStartDate = function (callback) {
    system_splashScreenModel.findOne({},{endDate:-1}).sort({'endDate':-1}).exec(callback);
}



